package com.temi.iot.config.datasource;


import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.baomidou.mybatisplus.mapper.ISqlInjector;
import com.baomidou.mybatisplus.mapper.LogicSqlInjector;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * springBoot集成mybatis的基本入口
 * 1）创建数据源
 * 2）创建SqlSessionFactory
 */
@Configuration
//该注解类似于spring配置文件
@MapperScan(basePackages = {"com.temi.iot.dao"})
public class MyBatisConfig {

    private final Environment pro;

    @Autowired
    public MyBatisConfig(Environment pro) {
        this.pro = pro;
    }

    /**
     * 创建数据源
     * 该注解表示在同一个接口有多个实现类可以注入的时候，默认选择哪一个，而不是让@autowire注解报错
     */
    @Bean(name = "ds")
    public DataSource getDataSource() throws Exception {
        Properties props = new Properties();
        props.put("driverClassName", pro.getProperty("jdbc.driverClassName"));
        props.put("url", pro.getProperty("jdbc.url"));
        props.put("username", pro.getProperty("jdbc.username"));
        props.put("password", pro.getProperty("jdbc.password"));
        props.put("testWhileIdle", pro.getProperty("jdbc.testWhileIdle"));
        props.put("maxActive", pro.getProperty("jdbc.maxActive"));
        props.put("initialSize", pro.getProperty("jdbc.initialSize"));
        props.put("maxWait", pro.getProperty("jdbc.maxWait"));
        props.put("poolPreparedStatements", pro.getProperty("jdbc.poolPreparedStatements"));
        props.put("maxPoolPreparedStatementPerConnectionSize", pro.getProperty("jdbc.maxPoolPreparedStatementPerConnectionSize"));
        props.put("connectionProperties", pro.getProperty("jdbc.connectionProperties"));
        props.put("minIdle", pro.getProperty("jdbc.minIdle"));
        props.put("timeBetweenEvictionRunsMillis", pro.getProperty("jdbc.timeBetweenEvictionRunsMillis"));
        props.put("minEvictableIdleTimeMillis", pro.getProperty("jdbc.minEvictableIdleTimeMillis"));
        props.put("validationQuery", pro.getProperty("jdbc.validationQuery"));
        props.put("testOnBorrow", pro.getProperty("jdbc.testOnBorrow"));
        props.put("testOnReturn", pro.getProperty("jdbc.testOnReturn"));
        props.put("filters", pro.getProperty("jdbc.filters"));
        return DruidDataSourceFactory.createDataSource(props);
    }

    /**
     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
     */
//    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }

    /**
     * 注入sql注入器
     */
    @Bean
    public ISqlInjector sqlInjector() {
        return new LogicSqlInjector();
    }
}